<template>
  <div class="app-container">
    <!--查询-->
    <el-row>
      <el-input style="width:200px;margin-right: 10px" v-model="tableQuery.sname" placeholder="数据名称"></el-input>
      <el-tooltip class="item" content="搜索" placement="top">
        <el-button icon="el-icon-search" circle @click="fetchData()"></el-button>
      </el-tooltip>
    </el-row>
    <div style="margin-bottom: 30px;"></div>
    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleCreate">{{textMap.create}}</el-button>
    <el-tooltip content="数据命名导入" placement="top">
      <el-button size="mini" type="primary" @click="fileImpt"><svg-icon icon-class="f-import" class-name="im-ex-icon" /> 导入</el-button>
    </el-tooltip>
    <el-tooltip content="数据命名全部导出" placement="top">
      <el-button size="mini" type="primary" @click="fileExptAll"><svg-icon icon-class="f-export" class-name="im-ex-icon" /> 全部导出</el-button>
    </el-tooltip>
    <el-tooltip content="数据命名选择导出" placement="top" v-if="batchOperate">
      <el-button size="mini" type="primary" @click="fileExpt"><svg-icon icon-class="f-export" class-name="im-ex-icon" /> 导出选择({{selectionRows.length}})</el-button>
    </el-tooltip>
    <el-tooltip content="数据命名批量删除" placement="top" v-if="batchOperate">
      <el-button size="mini" type="primary" @click="batchDelete"><svg-icon icon-class="f-export" class-name="im-ex-icon" /> 删除选择({{selectionRows.length}})</el-button>
    </el-tooltip>
    <div style="margin-bottom: 30px;"></div>
    <!--列表-->
    <el-table style="width: 100%"
              ref="stdTable"
              :data="tableData"
              v-loading.body="tableLoading"
              row-key="id"
              element-loading-text="Loading"
              @selection-change="tbSelChange"
              border fit highlight-current-row>
      <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="cn_name" label="中文名称" ></el-table-column>
      <el-table-column prop="alias" label="别名" ></el-table-column>
      <el-table-column prop="en_name" label="英文名称" ></el-table-column>
      <el-table-column prop="messure" label="单位"></el-table-column>
      <el-table-column prop="created_at" label="创建时间" ></el-table-column>
      <el-table-column prop="updated_at" label="更新时间" ></el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-tooltip content="命名编辑" placement="top">
            <el-link icon="el-icon-edit" @click="handleUpdate(scope.$index,scope.row)">编辑</el-link>
          </el-tooltip>
          <span style="margin:10px">|</span>
          <el-tooltip content="命名删除" placement="top">
            <el-link type="danger" icon="el-icon-delete" @click="handleDelete(scope.$index,scope.row)">删除</el-link>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-bottom: 30px;"></div>
    <!--分页-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="tablePage.current"
      :page-sizes="[20, 30, 40, 50, 60]"
      :page-size="tablePage.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tablePage.total">
    </el-pagination>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="80%" :close-on-click-modal="false" @close="closeDialog">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="150px" >
        <el-form-item label="ID" prop="id" v-if="dialogStatus=='update'">
          <el-input v-model="temp.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="单位" prop="messure">
          <el-autocomplete
            class="inline-input"
            v-model="temp.messure"
            :fetch-suggestions="querySearch"
            placeholder="请选择或输入单位"></el-autocomplete>
        </el-form-item>
        <el-form-item label="中文名称" prop="cn_name" >
          <el-input v-model="temp.cn_name"></el-input>
        </el-form-item>
        <el-form-item label="英文名称" prop="en_name">
          <el-input v-model="temp.en_name"></el-input>
        </el-form-item>
        <el-form-item label="别名" prop="alias">
          <el-input v-model="temp.alias"></el-input>
        </el-form-item>
        <el-form-item label="报表">
          <el-switch v-model="table_tag" />
        </el-form-item>
        <el-form-item label="按月录入">
          <el-switch v-model="month_tag" />
        </el-form-item>
        <el-form-item label="隐藏统计">
          <el-switch v-model="count_tag" />
        </el-form-item>
        <el-form-item label="函数">
          <el-switch v-model="fun_tag" />
        </el-form-item>
        <el-form-item label="公式编辑" v-if="fun_tag">
          <el-popover
            placement="top-start"
            trigger="focus">
            <el-select ref="fmSelect" v-model="choiceTag" placeholder="选择插入标签" filterable remote reserve-keyword :remote-method="tagFiltered" :loading="selectLoading" @change="fmTagSelectChange">
              <el-option v-for="(item,index) in filteredTags" :key="index" :label="item.cn_name" :value="item" />
            </el-select>
            <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6}" ref="fmInput" slot="reference" v-model="temp.func" @blur="fmBlur"/>
          </el-popover>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input type="number" v-model="temp.sort"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="temp.description"></el-input>
        </el-form-item>
        <el-form-item label="显示" prop="is_show">
           <el-checkbox v-model="temp.is_show"></el-checkbox>
        </el-form-item>
        <el-form-item label="创建时间" v-if="dialogStatus=='update'">
          <el-input v-model="temp.created_at" disabled></el-input>
        </el-form-item>
        <el-form-item label="更新时间" v-if="dialogStatus=='update'">
          <el-input v-model="temp.updated_at" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">创建</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog append-to-body :visible.sync="imptDialogVisible">
      <el-tag style="text-decoration: underline;cursor: pointer" @click.native="downloadTemp">模板下载</el-tag>
      <upload-excel @on-selected-file="uploadCallBack" />
    </el-dialog>

  </div>
</template>

<script>

  import {resetTemp,parseTime } from '@/utils'
  import { pageParamNames, confirm, messureList } from '@/utils/constants'
  import debounce from 'lodash/debounce'
  import uploadExcel from '@/components/UploadExcel'
  import {mapGetters} from 'vuex'
  import fieldsApi from "@/api/fields";


  export default {
    name: 'report-fields',
    components:{
      uploadExcel
    },
    computed:{
      ...mapGetters([
        'token'
      ]),
      batchOperate(){
        return this.selectionRows.length>0
      }
    },
    data() {
      return {
        tableLoading:false,
        imptDialogVisible:false,
        allTags:[],
        tableData: [],
        selectionRows:[],
        tableQuery:{
          sname: null
        },
        tablePage: {
          current: null,
          pages: null,
          size:null,
          total: null
        },
        dialogFormVisible: false,
        dialogStatus: '',
        count_tag:false,
        fun_tag:false,
        table_tag:false,
        month_tag:false,
        choiceTag:null,
        selectLoading:false,
        filteredTags:[],
        fmTagList:[],
        fmFocusIdx:-1,
        temp: {
          idx: null,//表格的下标
          id:null,
          type:'dcs',
          messure:null,
          cn_name: null,
          en_name: null,
          is_count:null,
          is_fun:null,
          is_table:null,
          is_month:null,
          func:null,
          dcs_standard_ids:null,
          alias:null,
          sort:10,
          description:null,
          is_show:true,
          created_at:null,
          updated_at:null
        },
        textMap: {
          update: '编辑',
          create: '新增'
        },
        messureList,
        rules: {
          cn_name: [{ required: true, message: '必填', trigger: 'blur' }],
          en_name:[{ required: true, message: '必填', trigger: 'blur' }],
          messure:[{ required: true, message: '必填', trigger: 'blur' }],
          alias:[{ required: true, message: '必填', trigger: 'blur' }]
        },
      }
    },

    created(){
      this.fetchData()
    },

    watch:{
      //延时查询
      'tableQuery.sname': debounce( function(){
        this.fetchData()
      },500),
      'temp.func':function(val, oldVal) {
        if (!oldVal&&val) {
          if (val.length===1&&val[0]==='['){
            this.fmTagList=[]
            this.$nextTick(() => { this.$refs['fmSelect'].toggleMenu(); });
          }
        }else if (oldVal&&!val){
          this.fmTagList=[]
          this.temp.func=null
        }else if (val&&val.length>oldVal.length){
          //输入中
          if (val[val.length-1]==='['&&val.substring(0,val.length-1)===oldVal){
            this.$nextTick(() => { this.$refs['fmSelect'].toggleMenu(); });
          }

        }else if (val&&val.length<oldVal.length){
          //删除中
           if (oldVal[oldVal.length-1]===']'&&oldVal.substring(0,oldVal.length-1)===val){
              let last_left_kh = val.lastIndexOf('[')
              if (last_left_kh!==-1){
                let del_tagname = val.substring(last_left_kh+1, val.length)
                this.delTagFromList(del_tagname)
                this.temp.func = val.substring(0,last_left_kh)
                if (!this.temp.func)
                  this.fmTagList=[]
              }
            }else{
               let delVal = oldVal[this.fmFocusIdx-1]
               if (delVal===']'){
                 let right_odlv = oldVal.substring(this.fmFocusIdx, oldVal.length)
                 let left_oldv = oldVal.substring(0, this.fmFocusIdx-1)
                 let last_left_kh = left_oldv.lastIndexOf('[')
                 if (last_left_kh!==-1){
                  let del_tagname = left_oldv.substring(last_left_kh+1, left_oldv.length)
                  this.delTagFromList(del_tagname)
                  this.temp.func = left_oldv.substring(0,last_left_kh)+right_odlv
                  this.$nextTick(() => { this.$refs['fmInput'].blur()  });

                }
               }
           }
        }
      }
    },//watch

    methods: {
      //分页
      handleSizeChange(val) {
        this.tablePage.size = val;
        this.fetchData();
      },
      handleCurrentChange(val) {
        this.tablePage.current = val;
        this.fetchData();
      },
      querySearch(queryString, cb) {
        let units = this.messureList;
        let results = queryString ? units.filter(this.createFilter(queryString)) : units;
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      //查询
      async fetchData() {
        this.tableLoading = true
        let res = await fieldsApi.dcsStandardQuery(this.tableQuery, this.tablePage)
        let nameddata = res.data
        this.tableData = nameddata.data
        this.tablePage.total= nameddata.total
        if(!this.tablePage.current)
          this.tablePage.current=1
        if(!this.tablePage.size)
          this.tablePage.size=20
        this.tableLoading = false
      },
      //更新
      async handleUpdate(idx,row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.idx = idx
        this.temp.is_show = Boolean(this.temp.is_show)
        this.count_tag=Boolean(this.temp.is_count)
        this.fun_tag=Boolean(this.temp.is_fun)
        this.table_tag=Boolean(this.temp.is_table)
        this.month_tag=Boolean(this.temp.is_month)
        const dcs_standard_ids = this.temp.dcs_standard_ids?this.temp.dcs_standard_ids.split(','):[]
        if (this.fun_tag){
          const res = await fieldsApi.dcsStandardList()
          this.allTags = res.data
          const choiceTags= this.allTags.filter(tag=>dcs_standard_ids.indexOf(tag.id.toString())>-1)
          this.filteredTags= choiceTags.map(tag=>{
            return {
              id:tag.id.toString(),
              cn_name:tag.cn_name
            }
          })
          this.fmTagList=Object.assign([],choiceTags)
        }

        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => this.$refs['dataForm'].clearValidate())
      },
      updateData() {
        if (this.fun_tag&&!this.temp.func){
          this.$message({
            type:'error',
            message:'公式不能为空'
          })
          return
        }
        this.$refs['dataForm'].validate((valid) => {
          if (!valid) return;
          this.dialogFormVisible = false
          let tempData = Object.assign({}, this.temp)//copy obj
          tempData.is_show = tempData.is_show?1:0
          tempData.is_count = this.count_tag?1:0
          tempData.is_fun = this.fun_tag?1:0
          tempData.is_table = this.table_tag?1:0
          tempData.is_month = this.month_tag?1:0
          if (this.fun_tag){
            const tagids = this.fmTagList.map(t=> t.id)
            tempData.dcs_standard_ids = tagids.join(',')
          }
          fieldsApi.updateStandardName(tempData.id,tempData).then(res => {
            this.dialogFormVisible = false
            this.$message.success('更新命名成功')
            this.fetchData()
          })
        })
      },

      //删除
      handleDelete(idx,row) {
        this.$confirm('您确定要永久删除该标准字段？', '提示', confirm).then(() => {
          fieldsApi.deleteStandardName( row.id ).then(res => {
            this.tablePage.total--
            this.dialogFormVisible = false
            const page_surplus = this.tablePage.total % this.tablePage.size
            const max_page = Math.ceil(this.tablePage.total/this.tablePage.size)
            if (!page_surplus&&this.tablePage.current>max_page)
              this.tablePage.current--
            this.$message.success('删除成功')
            this.selectionRows=[]
            this.$refs['stdTable'].clearSelection()
            this.fetchData()
          })
        }).catch(() => {
          this.$message.info('已取消删除')
        })
      },
      async batchDelete(){
        this.tableLoading=true
        for (let i=0;i<this.selectionRows.length;i++){
          const stdRow = this.selectionRows[i]
          await this.delRoop(stdRow.id)
        }
        this.$refs['stdTable'].clearSelection()
        this.selectionRows=[]
        this.tableLoading=false
        this.$message.success("批量删除成功!")
        this.tablePage.current=1
        this.fetchData()
      },
      delRoop(std_id){
        return new Promise(resolve => {
          fieldsApi.deleteStandardName( std_id ).then(res => {
            resolve(res)
          })
        })
      },
      //新增
      handleCreate() {
        resetTemp(this.temp)
        this.temp.type='dcs'
        this.temp.is_show=true
        this.temp.sort=10
        this.count_tag=false
        this.fun_tag=false
        this.table_tag=false
        this.month_tag=false
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => this.$refs['dataForm'].clearValidate())
      },
      createData() {
        if (this.fun_tag&&!this.temp.func){
          this.$message({
            type:'error',
            message:'公式不能为空'
          })
          return
        }
        this.$refs['dataForm'].validate((valid) => {
          if (!valid) return;
          let tempData = Object.assign({}, this.temp)
          tempData.is_show = tempData.is_show?1:0
          tempData.is_count = this.count_tag?1:0
          tempData.is_fun = this.fun_tag?1:0
          tempData.is_table = this.table_tag?1:0
          tempData.is_month = this.month_tag?1:0
          if (this.fun_tag){
            const tagids = this.fmTagList.map(t=> t.id)
            tempData.dcs_standard_ids = tagids.join(',')
          }
          fieldsApi.addStandardName(tempData).then((res) => {
              this.dialogFormVisible = false
              this.$message.success('添加成功')
              this.fetchData()
            })
        })
      },
      tagFiltered(query){
        const dbouceOpts=()=>{
          if (query !== '') {
            this.selectLoading = true;
            if (!query){
              query=""
            }
            fieldsApi.dcsStandardList({cn_name:query}).then(res=>{
              this.filteredTags = res.data
              this.selectLoading = false
            }).catch(err=>{
              this.selectLoading = false
              this.$message.error("无法读取tag列表,请查看数据库连接!")
            })
          } else {
            this.filteredTags = [];
          }
        }
        debounce(dbouceOpts,1500)()
      },
      delTagFromList(tag_name){
        let delIdx = -1
        for (let tidx in this.fmTagList){
          let tag = this.fmTagList[tidx]
          if (tag.cn_name===tag_name){
            delIdx = tidx
            break
          }
        }
        if (delIdx!==-1)
          this.fmTagList.splice(delIdx,1)
      },
      fmTagSelectChange(value){
        if (value===undefined)
          return
        if(!this.temp.func){
          this.temp.func = '['+value.cn_name+']'
        }else if (this.temp.func[this.temp.func.length-1]==='['){
          this.temp.func += value.cn_name+']'
        }else if(this.temp.func.length>this.fmFocusIdx){
          let fm_left = this.temp.func.substring(0, this.fmFocusIdx)
          let fm_right = this.temp.func.substring(this.fmFocusIdx,this.temp.func.length)
          this.temp.func = fm_left+'['+value.cn_name+']'+fm_right
        } else{
          this.temp.func +='['+value.cn_name+']'
        }
        this.fmTagList.push(Object.assign({},value))
        this.choiceTag=null
      },
      fmBlur(e){
        if (this.temp.func)
          this.fmFocusIdx = this.temp.func.length
      },
      closeDialog(){
        resetTemp(this.temp)
        this.filteredTags=[]
        this.fmTagList=[]
      },
      tbSelChange(rows){
        this.selectionRows = rows
      },
      fileImpt(){
        this.imptDialogVisible=true
      },
      fileExptAll(){
        this.exptCallBack(null)
      },
      fileExpt(){
        const sids = this.selectionRows.map(row=> row.id).join(',')
        this.exptCallBack(sids)
      },
      exptCallBack(ids){
        let title = '全部内容'
        if (ids)
          title='所选内容'
        const confirmTitle=`您确定要下载${title}？`
        this.$confirm(confirmTitle, '提示', confirm).then(() => {
          this.submitDataExport(ids)
        }).catch(() => {
          this.$message({type: 'info', message: '已取消导出'});
        });
      },
      uploadCallBack(excelData){
        const confirmTitle=`您确定要上传文件${excelData.name}？`
        this.$confirm(confirmTitle, '提示', confirm).then(() => {
          this.submitDataImport(excelData)
        }).catch(() => {
          this.$message({type: 'info', message: '已取消上传'});
          this.imptDialogVisible=false
        });
      },
      submitDataExport(ids){
        console.log(ids)
        const baseHost = 'http://analysisapi.wm-mis.com/api'
        let ids_query = 'all'
        if (ids)
          ids_query = ids
        const durl = `${baseHost}/dcs-standard/download?token=${this.token}&ids=${ids_query}`
        window.open((durl),"_self");
      },
      submitDataImport(excelData){
        const imptData = JSON.stringify(excelData)
        console.log(imptData)
        this.$message.success("上传成功")
        this.imptDialogVisible=false
        fieldsApi.imptStandards(imptData).then(res=>{
            if (res.code){
              return
            }
            this.$message.success("上传成功")
            this.imptDialogVisible=false
          })
      },
      downloadTemp(){
        let tmp_url = 'http://wmhb.wm-mis.com/report-standard-temp.xlsx'
        window.open((tmp_url),"_self");
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>

</style>
